const fs = require('fs');
const path = require("path");
const url = path.resolve();
//处理当前项目路径
function dealWithUplaodPath(){
    let dir = url.replace(/\\/g,'/').split('/');;
    dir.pop();
    return dir.join('/');
 };
//写入文件
function writeFile (data,path = `${dealWithUplaodPath()}/package.json` ){
    return new Promise((resolve,reject) =>{
        fs.writeFile(path, data, function(error, data) {
            //  用error来判断文件是否读取成功
            if (error){
                console.log("写入文件失败,内容是" + error.message)
                 reject({
                     code:-1,
                     data:error
                 }) ;
            }else resolve({code:0,data:'写入文件成功'});
          });
    })
};
// 读取文件
function readFile (){
    return new Promise((resolve,reject) =>{
        fs.readFile(`${dealWithUplaodPath()}/package.json`, "utf-8", function(error, data) {
            //用error来判断文件是否读取成功
            if (error){
                console.log("读取文件失败,内容是" + error.message)
                 reject({
                     code:-1,
                     data:error
                 }) ;
            }else resolve({code:0,data});
          });
    })
};

function deteFormat (fmt = "yyyy-MM-dd hh:mm:ss") { 
    let date = new Date();
    var o = { 
       "M+" : date.getMonth()+1,                 //月份
       "d+" : date.getDate(),                    //日
       "h+" : date.getHours(),                   //小时
       "m+" : date.getMinutes(),                 //分
       "s+" : date.getSeconds(),                 //秒
       "q+" : Math.floor((date.getMonth()+3)/3), //季度
       "S"  : date.getMilliseconds()             //毫秒
   }; 
   if(/(y+)/.test(fmt)) {
           fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length)); 
   }
    for(var k in o) {
       if(new RegExp("("+ k +")").test(fmt)){
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        }
    }
   return fmt; 
}

module.exports = {readFile,writeFile,dealWithUplaodPath ,deteFormat};